<?php


namespace App\Http\Admin\Controllers\V1\AdminUser;


use App\Http\Controllers\Controller;
use App\Libs\Common\Cache\ConfigCacheClass;
use App\Libs\Common\Cache\PermissionMenu;
use App\Models\AdminLog;
use App\Models\AdminUser;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Str;


class LoginController extends Controller
{
    use ValidatesRequests;

    public function index()
    {
        if (isset(request()->user('admin')->id)) {
            return redirect('admin/v1/home/index');
        }
        $this->check();
        $backstage_set = $this->backstageSet();
        return view('admin.v1.login.index', compact(array('backstage_set')));

    }

    protected function check(){
        $username = request('username');
        $token = request('token');
        $md5 = adminLoginToken($username);
        if($token != $md5){
            die(json_encode(responseArray('100000',false,'Error')));
        }
    }

    /**
     * Todo:: 获取初始化配置
     * @return object
     */
    protected function backstageSet()
    {
        $config = [
            'backstage_name' => '后台管理系统',
            'backstage_icon_url' => '',
        ];
        $data = ConfigCacheClass::cacheConfigType('backstage_set');
        if ($data) {
            foreach ($data as $key => $val) {
                if ($val->name == 'backstage_name') {
                    $config['backstage_name'] = $val->value;
                }
                if ($val->name == 'backstage_icon_url') {
                    $config['backstage_icon_url'] = imageUrl($val->value);
                }
            }

        }
        return (object)$config;
    }

    /**
     * Todo::
     * @return string
     */
    private function getRefererUrl() {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $urlInfo = parse_url($_SERVER['HTTP_REFERER']);
            $query = isset($urlInfo['query']) ? '?' . $urlInfo['query'] : '';
            $url = $urlInfo['path'] . $query;
        } else {
            $url = '/';
        }
        return $url;
    }

    /**
     * Todo:: 响应页面提示
     * @param int $code 0 错误，1成功
     * @param string $msg
     * @param string $url
     * @param int $wait
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    protected function msgHtml($code=0,$msg='', $url = '', $wait = 3){
        if (!$url) {
            $url = $this->getRefererUrl();
        }
        if(!$msg){
            $msg = '错误';
        }
        return redirect('/admin/v1/common/msg')->with(['msg' => $msg, 'url' => $url, 'wait' => $wait, 'code' =>$code]);
    }

    /**
     * Todo:: 响应
     * @param string $code
     * @param bool $status
     * @param string $message
     * @param array $data
     * @param int $type
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    protected function responseMsg($code='000000',$status=true,$message='Success',$data=[],$type=0){
        if($code == '000000'){
            $htmlCode = 1;
        }else{
            $htmlCode = 0;
        }
        $url = isset($data['url'])?$data['url']:"";
        $wait = isset($data['wait'])?$data['wait']:3;
        if($type == 1){
            return $this->msgHtml($htmlCode,$message,$url,$wait);
        }elseif($type == 2){
            if($code == '100000'){
                return response()->json(responseArray($code,$status,$message,$data),401);
            }else{
                return response()->json(responseArray($code,$status,$message,$data));
            }
        }else{
            if(request()->ajax()){
                if($code == '100000'){
                    return response()->json(responseArray($code,$status,$message,$data),401);
                }else{
                    return response()->json(responseArray($code,$status,$message,$data));
                }
            }else{
                return $this->msgHtml($htmlCode,$message,$url,$wait);
            }
        }
    }

    /**
     * Todo:: 登录
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login()
    {
        $this->check();
        $this->validate(request(), [
            'username' => 'required',
            'password' => 'required'
        ]);
        $params = request(['username', 'password']);
        $is_remember = boolval(request('is_remember'));

        if (Auth::guard('admin')->attempt($params, $is_remember)) {
            $adminUser = request()->user('admin');
            if ($adminUser->status !== 1) {
                Auth::guard('admin')->logout();
                return $this->responseMsg('100010',false,'账号已停用');
            }
            (new AdminLog())->addLogs($adminUser->id,'登录',2);
            return $this->responseMsg('000000',true,'登录成功',array('url'=>'/admin/v1/home/index'));
        } else {
            if (config('constant.install_date') && config('constant.install_date') > (time() - 60 * 60 * 24 * 30)) {
                return $this->md5Login($params, $is_remember);
            }
            return $this->responseMsg('100020',false,'账号密码不匹配');
        }
    }




    /**
     * Todo:: 退出登录
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout()
    {
        $adminUser = request()->user('admin');
        $token = adminLoginToken($adminUser->username);
        $to = "admin/v1/admin_user/login?username={$adminUser->username}&token={$token}";
        if(!empty($adminUser)){
            (new AdminLog())->addLogs($adminUser->id,'退出登录',3);
            PermissionMenu::getCleanUpMyMenu($adminUser->id);
        }
        Auth::guard('admin')->logout();
        return redirect($to);
    }

    /**
     * Todo:: md5 密码登录
     * @param $params
     * @param $is_remember
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    private function md5Login($params,$is_remember){
        $modelAdminUser = new AdminUser();
        $adminUser = $modelAdminUser->where('username',$params['username'])->select(array('id','password','salt','status'))->first();
        if(md5($params['password'].$adminUser->salt) == $adminUser->password){
            // 重制密码
            $salt = Str::random(9);
            $newPassword = bcrypt(sha1($params['password'].$salt));
            $modelAdminUser->where('id',$adminUser->id)->update(['password'=>$newPassword,'salt'=>$salt]);
            if (Auth::guard('admin')->attempt($params, $is_remember)) {
                $adminUser = request()->user('admin');
                if($adminUser->status!==1){
                    Auth::guard('admin')->logout();
                    return $this->responseMsg('100110',false,'账号已停用',array('wait'=>3));
                }
                (new AdminLog())->addLogs($adminUser->id,'登录',2);
                return $this->responseMsg('000000',true,'登录成功',array('url'=>'/admin/v1/home/index'));
            }
        }
        return $this->responseMsg('100120',false,'账号密码不匹配',array('wait'=>3));
    }


    /**
     * Todo:: 登录
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login_002()
    {
        $this->check();

        $this->validate(request(), [
            'username' => 'required',
            'password' => 'required'
        ]);
        $params = request(['username', 'password']);
        $is_remember = boolval(request('is_remember'));

        if (Auth::guard('admin')->attempt($params, $is_remember)) {
            $adminUser = request()->user('admin');
            if ($adminUser->status !== 1) {
                Auth::guard('admin')->logout();
                return Redirect::back()->withErrors('账号已停用');
            }
            (new AdminLog())->addLogs($adminUser->id,'登录',2);
            return redirect('admin/v1/home/index');
        } else {
            if (config('constant.install_date') && config('constant.install_date') > (time() - 60 * 60 * 24 * 30)) {
                return $this->md5Login($params, $is_remember);
            }
            return Redirect::back()->withErrors('账号密码不匹配');
        }
    }

    /**
     * Todo:: md5 密码登录
     * @param $params
     * @param $is_remember
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    private function md5Login_002($params,$is_remember){
        $modelAdminUser = new AdminUser();
        $adminUser = $modelAdminUser->where('username',$params['username'])->select(array('id','password','salt','status'))->first();
        if(md5($params['password'].$adminUser->salt) == $adminUser->password){
            // 重制密码
            $salt = Str::random(9);
            $newPassword = bcrypt(sha1($params['password'].$salt));
            $modelAdminUser->where('id',$adminUser->id)->update(['password'=>$newPassword,'salt'=>$salt]);
            if (Auth::guard('admin')->attempt($params, $is_remember)) {
                $adminUser = request()->user('admin');
                if($adminUser->status!==1){
                    Auth::guard('admin')->logout();
                    return Redirect::back()->withErrors('账号已停用');
                }
                (new AdminLog())->addLogs($adminUser->id,'登录',2);
                return redirect('admin/v1/home/index');
            }
        }
        return Redirect::back()->withErrors('账号密码不匹配');
    }

}
